package com.android.settings.ios.wallpaper;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;

import com.android.settings.ios.R;
import com.android.settings.ios.SettingsMainActivity;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class WallpaperSelectFragment extends Fragment {

    protected String mMainTitle;
    protected String mBackSubTitle;

    private int mCurrentRotation;
    private GridView mGridView;
    private WallAdapter mAdapter;
    private final List<File> mItemList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBackSubTitle = bundle.getString("fragment_back", null);
            mMainTitle = bundle.getString("fragment_title", getString(R.string.app_name));
        }

        WindowManager wm = getActivity().getSystemService(WindowManager.class);
        mCurrentRotation = wm.getDefaultDisplay().getRotation();
        orderByName("/system/media/wallpaper/", "thumb_");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.os_wallpaper_select_fragment, null);
        mAdapter = new WallAdapter(getContext(), mItemList);
        mGridView = view.findViewById(R.id.wall_grid_view);
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                File file = mItemList.get(position);
                String name = file.getName().replace("thumb_", "wallpaper_");
                Intent intent = new Intent(getActivity(), WallpaperSetActivity.class);
                intent.putExtra("file_path", file.getParent() + "/" + name);
                getActivity().startActivity(intent);
            }
        });
        if (mCurrentRotation == 1 || mCurrentRotation == 3) {
            mGridView.setNumColumns(3);
        }
        return view;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_USER) {
            mGridView.setNumColumns(3);
        } else {
            mGridView.setNumColumns(2);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateTitleIfNeeded();
    }

    protected void updateTitleIfNeeded() {
        Activity activity = getActivity();
        if (activity instanceof SettingsMainActivity) {
            activity.setTitle(mMainTitle);
            ((SettingsMainActivity) activity).setLeftBackText(mBackSubTitle);
        }
    }

    private void orderByName(String filePath, String start) {
        File[] files = new File(filePath).listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.getName().startsWith(start);
            }
        });
        if (files != null) {
            Collections.addAll(mItemList, files);
        }
        mItemList.sort(new Comparator<File>() {

            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    private class WallAdapter extends ArrayAdapter<File> {

        private LayoutInflater mInflater;

        public WallAdapter(Context context, List<File> objects) {
            super(context, -1, objects);
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            File file = getItem(position);
            convertView = mInflater.inflate(R.layout.os_wallpaper_item, null);
            ImageView imageView = convertView.findViewById(android.R.id.icon);
            imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            return imageView;
        }
    }
}
